/*-----------------------------------------------------------------------------------
Name: Sangyoon Park
Date: January 25 2023
This do file does : 
	Create tables for Spillover analysis (Online Appendix F)
-----------------------------------------------------------------------------------*/
clear all
set matsize 10000
set maxvar 10000
set more off
capture log close


#delim ;


/*-----------------------------------------------------------------------------------
			 Set up
-----------------------------------------------------------------------------------*/
*** Setting up files;
	glo datafile "qu_analysis"; 	// type in the name of the datafile that you want to create;

*** Set up program;
 ** Number Format;
	capture program drop autoformat;
	program define autoformat;

	if int(`1')==`1' global format "%12.0f";
	else if abs(`1')>10 global format "%9.1f";
	else if abs(`1')>1 global format "%9.2f";
	else if abs(`1')>.1 global format "%9.3f";
	else if abs(`1')>.01 global format "%9.3f";
	else if abs(`1')>.001 global format "%9.3f";
	else if abs(`1')>.0001 global format "%9.4f";
	else if abs(`1')<.00001 global format "%9.5f";

	end;
	
 ** Tex Table format;
  	capture program drop head_foot;
	program define head_foot;

	syntax, [caption(str)] [label(str)] [notes(str)] [size(str)] [columns(str)] [sideways] [long];

	local estimates=r(names);
	if "`columns'"=="" local columns:word count `estimates';
	if "`sideways'"=="sideways" local table sidewaystable;
	if "`long'"=="long" local table longtable;
	else local table table;
	local col = `columns'+1;

	global header \begin{`table'}[H] \footnotesize \begin{center};
		if "`size'"!="" global header $header \begin{`size'};
		if "`caption'"!="" global header $header \caption{`caption'\label{table:`label'}} ;
		global header $header  ///;
		\begin{adjustbox}{max width=\textwidth} ///;
		\begin{threeparttable} ///;
		\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} ;
		global header $header ///;
		\begin{tabular}{l*{`columns'}{c}}\toprule[1.5pt];

	global header_mid \tabularnewline;

	global panel_title \multicolumn{`col'}{l}{Panel}\tabularnewline \midrule;

	global footer_mid \midrule ;
	global footer \bottomrule[1.2pt] ///
		\end{tabular} ;
		if "`notes'"!="" {;
			global footer $footer \begin{tablenotes}[flushleft] ///;
			`notes' ///;
			\end{tablenotes} ;
			};
		global footer $footer \end{threeparttable}\end{adjustbox};
		if "`size'"!="" global footer $footer \end{`size'};
		global footer $footer \end{center} \end{`table'} 	;
	end;

*** table setting;
	local stat_balance cells("mean(fmt(2)) b(fmt(3) star)" "sd(par fmt(2)) t(par fmt(2))") ///;
			label noobs collabels(none) nonote ;
	local stat_table cells("mean(fmt(2))" "sd(par fmt(2))") label collabels(none) nonote ;

	local reg_table_format cells(b(fmt(3) star) se(par fmt(3))) star(* 0.10 ** 0.05 *** 0.01) ///;
		stats(N r2 ymean, fmt(0 3 2) labels("N" "R-Squared" "Mean of Dep. Var."))  ///;
		label mlabels(none) collabels(none) nonotes;

	local reg_table_format2 cells(b(fmt(3) star) se(par fmt(3))) star(* 0.10 ** 0.05 *** 0.01) ///;
		stats(ymean, fmt(3) labels("Mean of Dep. Var."))  ///;
		label mlabels(none) collabels(none) nonotes;

	
*** Read data;
	
	use "${data_path}/FARMER_LONG_SETUP", replace;
	
*** Keep control communes;

	keep if st_tgroup == 1 | st_tgroup == 5 ;	
	
*** Generate dummy for treatment groups;	
	
	gen tr_spill = (control_commune == 0);

*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen certelig = (st_tgroup == 5);

*** Drop large farms (top 1 percent in terms of farm size);

	drop if ha_whitedragon >= 5;
	
	gen post = (round == 1 | round == 2);
	gen postXtr_spill = post*tr_spill;
	gen postXfarmer_in2 = post*farmer_in2;
	gen postXtrader_in2 = post*trader_in2;	
	
** Generate distance;
gen distance = 12.2 if commune == "Ham Chinh";
replace distance = 22.3 if commune == "Ham Cuong";
replace distance = 11.6 if commune == "Ham Hiep";
replace distance = 13.5 if commune == "Ham Liem";
replace distance = 25.9 if commune == "Ham Minh";
replace distance = 11 if commune == "Ham My";
replace distance = 29.5 if commune == "Ham Phu";
replace distance = 6.1 if commune == "Ham Thang";
replace distance = 32.5 if commune == "Ham Tri";
replace distance = 32.1 if commune == "Hong Liem";
replace distance = 22.5 if commune == "Hong Son";
replace distance = 61.6 if commune == "Hong Thai";
replace distance = 17.2 if commune == "Ma Lam";
replace distance = 18.9 if commune == "Muong Man";
replace distance = 8.1 if commune == "Phu Long";
replace distance = 38 if commune == "Tan Lap";
replace distance = 50.5 if commune == "Tan Nghia";
replace distance = 6.9 if commune == "Tien Loi";
gen ldistance = log(distance);	
	
*** Define local variables;
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8;
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base gap_comply_base hours_base log_totalvolume_base log_price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base ldistance;	
	
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;
	
/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var tr_spill "Control Group in Treated Regions";
	lab var postXtr_spill "Post Training $\times$ Control Farmer in Treated Districts";



/*-----------------------------------------------------------------------------------
			 		OUTCOME = Baseline
-----------------------------------------------------------------------------------*/	
local baseline "age female edu_second exp_dragon ha_whitedragon tree_whitedragon anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base cost_fert_base cost_pest_base cost_facequip_base cost_labor_base cost_utility_base cost_total_base attrit_fu1 attrit_fu2";



gen log_totalvolume_base = log(totalvolume_base+1);
gen log_price_base = log(price_base+1);
replace cost_fert_base = 0 if cost_fert_base ==.;
replace cost_pest_base = 0 if cost_pest_base ==.;
replace cost_facility_base = 0 if cost_facility_base ==.;
replace cost_equip_base = 0 if cost_equip_base ==.;
replace cost_labor_base = 0 if cost_labor_base ==.;
replace cost_utility_base = 0 if cost_utility_base ==.;
replace cost_other_base = 0 if cost_other_base ==.;

replace totalvolume_base = totalvolume_base / 1000;
replace price_base = price_base / 1000;
replace revenue_base = revenue_base / 1000000;
replace price = price / 1000 if round == 0;
replace totalvolume = totalvolume / 1000 if round == 0;
replace log_price = log_price_base if round == 0;
replace log_totalvolume = log_totalvolume_base if round == 0;
replace cost_costtotal = cost_costtotal / 1000000 if round == 0;
replace revenue = revenue / 1000000 if round == 0;
replace profit = revenue - cost_costtotal if round == 0;


gen cost_costtotal_base = cost_fert_base + cost_pest_base + cost_facility_base + cost_equip_base + cost_labor_base + cost_utility_base + cost_other_base;
drop if cost_costtotal_base == .;
replace cost_costtotal_base = cost_costtotal_base /1000000;


gen profit_base = revenue_base - cost_costtotal_base;

gen log_costtotal_base = log(cost_costtotal_base+1);
gen log_revenue_base = log(revenue_base+1);
gen log_profit_base = log(profit_base+1);

	
** Setting;
	loc titles "& Age & Female & Education & Experience & Size (Tree) & Volume & Price & Revenue & Cost & Profit \\ ";
	loc numbers "& (1) & (2) & (3) & (4) & (5) & (6) & (7) & (8) & (9) & (10) \\ \midrule";
	loc reg_table cells(b(fmt(3) star) se(par fmt(3)) p(fmt(3))) starlevels(* 0.10 ** 0.05 *** 0.01) ///
		stats(ymean_control r2 N, fmt(2 2 0) ///
		labels("Control mean (Pass/Total)" "R-squared" "Observations"))  ///
		label mlabels(none) collabels(none) nonotes nonumbers posthead("`titles'" "`numbers'") ///
		mgroups("Baseline Difference", pattern(1 0 0 0 0 0 0 0) ///
		span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cmidrule(lr){@span})) ///
		;


** Estimation;
	local outcome "age female edu_second exp_dragon tree_whitedragon";

		foreach y of local outcome {;
	
		eststo: qui reg `y' tr_spill certelig ldistance if round == 1, robust cluster(group_id);
		estadd ysumm;
		qui sum `y' if tr_spill == 0;
		qui estadd scalar ymean_control = r(mean);
		};		

	
** Estimation;
	local outcome "totalvolume_base price_base";

		foreach y of local outcome {;
	
		eststo: qui reg log_`y' tr_spill certelig ldistance if round == 2, robust cluster(group_id);
		estadd ysumm;
		qui sum `y' if tr_spill == 0;
		qui estadd scalar ymean_control = r(mean);
		};
		
** Estimation;
	local outcome "revenue_base cost_costtotal_base profit_base";

		foreach y of local outcome {;
	
		eststo: qui reg `y' tr_spill certelig ldistance if round == 2, robust cluster(group_id);
		estadd ysumm;
		qui sum `y' if tr_spill == 0;
		qui estadd scalar ymean_control = r(mean);
		};		
	
** Table;
	loc colnum 10;
	local caption Balance Check between untreated and treated control;
	local label baseline_spillover_pool;
	local notes `notes_gap';

head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum');

esttab  ///;
using "${table_path}/reg_baseline_spillover.tex", replace ///
	keep(tr_spill) `reg_table' ///
	prehead("$header") postfoot("$footer") substitute("\_" "_");

est clear;

	
/*-----------------------------------------------------------------------------------
			 		OUTCOME = GAP AUDIT
-----------------------------------------------------------------------------------*/;

** Setting;
	loc titles "& Knowledge & Awareness & Total & Pesticide \\ ";
	loc numbers "& (1) & (2) & (3) & (4) \\ \midrule";
	loc reg_table cells(b(fmt(3) star) se(par fmt(3)) p(fmt(3))) starlevels(* 0.10 ** 0.05 *** 0.01) ///
		stats(ymean_control r2 N, fmt(2 2 0) ///
		labels("Control mean (Pass/Total)" "R-squared" "Observations"))  ///
		label mlabels(none) collabels(none) nonotes nonumbers posthead("`titles'" "`numbers'") ///
		mgroups("Self report" "Audit report on Compliance", pattern(1 0 1 0) ///
		span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cmidrule(lr){@span})) ///
		;

** Estimation;
	local outcome "knowledge perception";

		foreach y of local outcome {;
	
		eststo: qui reg std_`y' tr_spill certelig `balance'  ldistance if round == 1, robust cluster(group_id);
		estadd ysumm;
		qui sum raw_`y' if tr_spill == 0;
		qui estadd scalar ymean_control = r(mean);
		};		
		
** Estimation;
	local outcome "score pestman";

		foreach y of local outcome {;
	
		eststo: qui reg std_`y' tr_spill certelig `balance'  ldistance i.round, robust cluster(group_id);
		estadd ysumm;
		qui sum audit_`y' if tr_spill == 0;
		qui estadd scalar ymean_control = r(mean);
		};
	
** Table;
	loc colnum 4;
	local caption Spillover Effects on Farmer's Knowledge, Awareness, and Compliance;
	local label audit_spillover_pool;
	local notes `notes_gap';

head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum');

esttab  ///;
using "${table_path}/reg_audit_spillover_pool.tex", replace ///
	keep(tr_spill) `reg_table' ///
	prehead("$header") postfoot("$footer") substitute("\_" "_");

est clear;

/*-----------------------------------------------------------------------------------
			 		OUTCOME = PESTICIDE RESIDUE
-----------------------------------------------------------------------------------*/

** Setting;
	loc titles "& Residue & China & Japan & EU  & US \\ ";
	loc numbers "& (1)\& (2) & (3) & (4) & (5)\ \midrule";
	loc reg_table cells(b(fmt(3) star) se(par fmt(3)) p(fmt(3))) starlevels(* 0.10 ** 0.05 *** 0.01) ///
		stats(ymean_control r2 N, fmt(2 2 0) ///
		labels("Control mean" "R-squared" "Observations"))  ///
		label mlabels(none) collabels(none) nonotes nonumbers posthead("`titles'" "`numbers'") ///
		mgroups("Mean"  "Compliance", pattern(1 1 0 0 0) ///
		span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cmidrule(lr){@span})) ///
		;


		
** Estimation;
	local outcome "mean_std_pest_eu comply_china comply_japan comply_eu comply_us";

		foreach y of local outcome {;
	
		eststo: qui reg `y' tr_spill certelig `balance'  ldistance if round== 2 & mean_std_pest_eu != ., robust cluster(group_id);
		estadd ysumm;

		qui sum `y' if tr_spill == 0 & round == 2 & mean_std_pest_eu != .;
		qui estadd scalar ymean_control = r(mean);
		};
	
** Table;
	loc colnum 5;
	local caption Spillover Effects on Pesticide Residue;
	local label pesticide_spillover;

head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum');

esttab  ///;
using "${table_path}/reg_pesticide_spillover.tex", replace ///
	keep(tr_spill) `reg_table' ///
	prehead("$header") postfoot("$footer") substitute("\_" "_");

est clear;
	

/*-----------------------------------------------------------------------------------
			 		OUTCOME = PRODUCT ATTRIBUTES
-----------------------------------------------------------------------------------*/	

** Setting;
	loc titles "& Sweetness & Skin & Bract & Length & Width & Weight & Mean \\ \cmidrule{2-8}";
	loc numbers "& (1) & (2) & (3) & (4) & (5) & (6) & (7) \\ \midrule";
	loc reg_table cells(b(fmt(3) star) se(par fmt(3)) p(fmt(3))) starlevels(* 0.10 ** 0.05 *** 0.01) ///
		stats(ymean_control r2 N, fmt(2 2 0) ///
		labels("Control mean (in raw units)" "R-squared" "Observations"))  ///
		label mlabels(none) collabels(none) nonotes nonumbers posthead("`titles'" "`numbers'") ///
		;


** Estimation;
	local outcome "sweet skin bract length width weight meanquality";

		foreach y of local outcome {;
	
		eststo: qui reg std_`y' tr_spill `balance' ldistance i.round, robust cluster(group_id);
		estadd ysumm;
		qui sum std_`y' if tr_spill == 0;
		qui estadd scalar ymean_control = r(mean);
		};
	
** Table;
	loc colnum 7;
	local caption Spillover Effects on Standardized Product Attributes;
	local label attribute_spillover_pool;

head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum');

esttab  ///;
using "${table_path}/reg_attribute_spillover_pool.tex", replace ///
	keep(tr_spill) `reg_table' ///
	prehead("$header") postfoot("$footer") substitute("\_" "_");

est clear;

/*-----------------------------------------------------------------------------------
			 		OUTCOME = REVENUE AND PROFIT
-----------------------------------------------------------------------------------*/	

** Generate variable;
set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;
drop if profit == .;
drop if log_revenue_base == 0;
drop if log_price_base == 0;

drop if log_costtotal_base == 0;
drop if log_profit_base == 0;
drop if log_totalvolume_base == 0;	

local outcome "price totalvolume";
foreach y of local outcome {;
gen log_`y'_dif = log_`y' - log_`y'_base;
gen `y'_dif = `y' - `y'_base;
	};
	
local outcome "revenue cost_costtotal profit";
foreach y of local outcome {;
gen `y'_dif = `y' - `y'_base;
	};	

drop if profit_dif == .;	

	
** Setting;
	loc titles "& Price & Volume & Revenue & Cost & Profit \\ \cmidrule{2-6}";
	loc numbers "& (1) & (2) & (3) & (4) & (5) \\ \midrule";
	loc reg_table cells(b(fmt(3) star) se(par fmt(3)) p(fmt(3))) starlevels(* 0.10 ** 0.05 *** 0.01) ///
		stats(ymean_control r2 N, fmt(2 2 0) ///
		labels("Control mean (in levels)" "R-squared" "Observations"))  ///
		label mlabels(none) collabels(none) nonotes nonumbers posthead("`titles'" "`numbers'") ///
		mgroups("Farm Sales", pattern( 1 0 0 0 0) ///
		span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cmidrule(lr){@span})) ///
		;


	
** Estimation;
	local outcome "price totalvolume";

		foreach y of local outcome {;

		preserve;
		sort round log_`y' randnum;
		bys round: drop if _n <= 2 | _n > _N-2;
	
		eststo: qui reg log_`y'_dif tr_spill certelig `balance'  i.round, robust cluster(group_id);
		

		estadd ysumm;
		qui sum `y' if tr_spill == 0 & post == 1;
		qui estadd scalar ymean_control = r(mean);
		restore;
		};
		
	local outcome "revenue cost_costtotal profit";

		foreach y of local outcome {;
		preserve;
		sort round `y' randnum;
		bys round: drop if _n <= 2 | _n > _N-2;		
	
		eststo: qui reg `y'_dif tr_spill certelig `balance' i.round, robust cluster(group_id);
		
		estadd ysumm;
		qui sum `y' if tr_spill == 0 & post == 1;
		qui estadd scalar ymean_control = r(mean);
		restore;
		};
		
		
		
** Table;
	loc colnum 5;
	local caption Spillover Effects on Farm Sales;
	local label farmsales_spillover_pool;

head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum');

esttab  ///;
using "${table_path}/reg_farmsales_spillover_pool.tex", replace ///
	keep(tr_spill) `reg_table' ///
	prehead("$header") postfoot("$footer") substitute("\_" "_");

est clear;


	
